<!--
 * @Description: 软终端 - 配置监控页
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-09-06 18:50:30
 * @LastEditTime: 2021-10-02 15:50:22
 * @LastEditors: 0001100986/LiuShuai
-->
<template>
  <div class="device device-port">
    <div class="title">
      <i
        class="iconfont icon-alter"
        style="color: rgb(24, 144, 255); background: rgb(230, 247, 255);"
      ></i> 隧道监控
    </div>
    <div class="content">
      <el-row>
        <el-col :xs="24" :sm="12" :lg="12">
          <el-radio-group v-model="type">
            <el-radio-button label="自定义"></el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="12" v-if="type==='自定义'">
          <el-date-picker
            v-model="dayTimes"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="otherInit"
            :picker-options="options"
          ></el-date-picker>
        </el-col>
      </el-row>
      <div id="charts" style="min-height: 400px;" v-loading="loading"></div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { Chart } from '@antv/g2';

export default {
  name: 'tunnel',
  props: ['introduce'],
  data () {
    return {
      type: '自定义',
      loading: false,
      portChart: null,
      portData: [],
      // 时间区间
      dayTimes: [dayjs(dayjs().subtract(7, 'day').format('YYYY-MM-DD') + ' 00:00:00').format(), dayjs(dayjs().subtract(1, 'day').format('YYYY-MM-DD') + ' 23:59:59').format()],
      // 可选时间范围
      options: {
        disabledDate (time) {
          // 昨天时间戳
          let end = dayjs(dayjs().subtract(1, 'day').format('YYYY-MM-DD') + ' 23:59:59').valueOf();
          // 一个月
          let one = 30 * 24 * 3600 * 1000;
          // 昨天30天前时间戳
          let start = end - one;
          return time.getTime() < start || time.getTime() > end;
        }
      }
    };
  },
  filters: {
    filterBPS (value) {
      if (value >= 0 && value < 1000) {
        value = value + 'bps';
      }
      if (value >= 1000 && value < 1000000) {
        value = (value / 1000).toFixed(2) + 'Kbps';
      }
      if (value >= 1000000) {
        value = (value / 1000000).toFixed(2) + 'Mbps';
      }
      return value;
    }
  },
  // 销毁
  beforeDestroy () {
    let _this = this;
    // 执行销毁定时器
    _this.clearPortChart();
  },
  watch: {
    type: {
      handler (val) {
        let _this = this;
        if (val === '自定义') {
          _this.clearPortChart();
          _this.otherInit();
        }
      }
    }
  },
  // DOM加载完成后执行
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      // 重置实时统计数据
      _this.portData = [];
      let charts = document.getElementById('charts');
      if (charts) {
        document.getElementById('charts').innerHTML = '';
      }
      _this.otherInit();
    });
  },
  methods: {
    // 清除定时器
    clearPortChart () {
      let _this = this;
      // 重置实时统计数据
      _this.portData = [];
      let charts = document.getElementById('charts');
      if (charts) {
        // 销毁chart
        document.getElementById('charts').innerHTML = '';
      }
    },
    // 自定义监控
    otherInit () {
      let _this = this;
      _this.clearPortChart();
      // 创建图表
      _this.portChart = new Chart({
        container: 'charts',
        autoFit: true,
        height: 400
      });
      _this.loading = true;
      // X轴显示格式
      _this.portChart.scale('year', {
        type: 'time',
        mask: 'YYYY-MM-DD HH:mm:ss'
      });
      // Y轴参数设置
      _this.portChart.scale('value', {
        nice: true,
        min: 0
      });
      // 图表提示框设置
      _this.portChart.tooltip({
        showCrosshairs: true,
        shared: true,
        customItems: (items) => {
          items.map(ind => {
            if (ind.name === '隧道接收流量速率' || ind.name === '隧道发送流量速率') {
              ind.value = _this.$options.filters['filterBPS'](ind.value);
            }
            if (ind.name === '丢包率') {
              ind.value = ind.value + '%';
            }
            if (ind.name === '抖动' || ind.name === '时延') {
              ind.value = ind.value + 'ms';
            }
          });
          return items;
        },
      });
      // 显示文字色值
      _this.portChart.line().position('year*value').color('country', ['#6495fa', '#5ad8a6', '#D47625', '#60A38B', '#9359dc']);
      _this.dayTimes = _this.dayTimes ? _this.dayTimes : [];
      if (_this.dayTimes.length === 0) {
        _this.$message.info('自定义最大监控范围：30天前0点 - 昨天24点');
        let charts = document.getElementById('charts');
        if (charts) {
          document.getElementById('charts').innerHTML = '';
        }
        _this.loading = false;
      } else {
        _this.$http.post({
          url: '/api/sdwan/vpn/server/log',
          data: {
            deviceId: _this.introduce.deviceId,
            daytimes: _this.dayTimes
          }
        }).then(res => {
          let { status, resultBody } = res;
          if (status === '0') {
            if (resultBody.objects.length === 0) {
              _this.$message.warning('暂无数据！');
              _this.portChart.changeData([]);
              _this.loading = false;
            } else {
              let arry = [];
              for (let i = 0; i < resultBody.objects.length; i++) {
                arry.push({
                  country: '隧道接收流量速率',
                  year: resultBody.objects[i].createTime.substr(0, 19),
                  value: resultBody.objects[i].upStreamRate
                });
                arry.push({
                  country: '隧道发送流量速率',
                  year: resultBody.objects[i].createTime.substr(0, 19),
                  value: resultBody.objects[i].downStreamRate
                });
                arry.push({
                  country: '时延',
                  year: resultBody.objects[i].createTime.substr(0, 19),
                  value: resultBody.objects[i].latency
                });
                arry.push({
                  country: '丢包率',
                  year: resultBody.objects[i].createTime.substr(0, 19),
                  value: resultBody.objects[i].loss
                });
                arry.push({
                  country: '抖动',
                  year: resultBody.objects[i].createTime.substr(0, 19),
                  value: resultBody.objects[i].jitter
                });
              }
              _this.portChart.changeData(arry);
              _this.loading = false;
            }
          }
        });
        _this.portChart.render();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.device {
  width: 100%;
  background: #fff;
  position: relative;
  box-sizing: border-box;
  border-radius: 3px;
  .title {
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    color: #555;
    font-size: 15px;
    i {
      border-radius: 50%;
      padding: 3px;
      margin-left: 10px;
    }
  }
  .content {
    padding: 15px;
    ::v-deep .el-radio-group {
      margin-bottom: 15px;
    }
    ::v-deep .el-alert {
      margin-bottom: 15px;
    }
    ::v-deep .el-date-editor {
      float: right;
    }
  }
}

@media only screen and (max-width: $device-ipad) {
  .device {
    .content {
      ::v-deep .el-date-editor {
        width: 100%;
        float: left;
        margin-bottom: 15px;
      }
    }
  }
}
</style>
